package com.feihong.txgw.ui.fragment.home;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.LogUtils;
import com.feihong.txgw.R;
import com.feihong.txgw.ui.activity.HomeActivity;
import com.feihong.txgw.ui.activity.order.ToCreateOrderActivity;
import com.feihong.txgw.ui.activity.user.MyShopCartActivity;
import com.feihong.txgw.ui.mvp.BaseMVPCompatFragment;
import com.feihong.txgw.ui.mvp.precenter.AbBasePrecenter;
import com.feihong.txgw.inter.contract.shopcar.IShopCarContract;
import com.feihong.txgw.message.LoginMessage;
import com.feihong.txgw.message.UpdateCartMessage;
import com.feihong.txgw.model.greendao.ShopCarGoodsModel;
import com.feihong.txgw.shopcar.adapter.ShopCarAdapter;
import com.feihong.txgw.shopcar.adapter.ShopCarRecommendAdapter;
import com.feihong.txgw.shopcar.bean.TerminalEntiyt;
import com.feihong.txgw.shopcar.listener.GoodsCountChangeListener;
import com.feihong.txgw.shopcar.listener.GoodsSelectStatusListener;
import com.feihong.txgw.shopcar.listener.ShopCarDelFailureGoodsListener;
import com.feihong.txgw.tx_precenter.ShopCarMainPrecenter;
import com.feihong.txgw.utils.CommonUtils;
import com.feihong.txgw.utils.PreferenceTools;
import com.feihong.txgw.utils.ScreenUtil;
import com.feihong.txgw.utils.UserLoginInfo;
import com.feihong.txgw.utils.greendao.GreenDaoOperateHelper;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * @Author wangziheng
 * @ProjectName txgw_app
 * @ClassName ShopCarFragment
 * @package com.feihong.txgw.ui.fragment.home
 * @data 2018/5/2 11:59
 * @Describe  待优化
 *              1、布局优化  重用view 减少层次
 *              2、代码优化  去除无用对象  多用组合
 * @Change
 */
public class ShopCarFragment extends BaseMVPCompatFragment<IShopCarContract.AbShopCarMainPrecenter> implements IShopCarContract.IShopCarMainView,View.OnClickListener {
    private static final String NORMAL = "NORMAL";
    private static final String UPDATE = "UPDATE";
    private static final String DEL = "DEL";
    /**
     * 标题栏
     */
    @BindView(R.id.img_btn_message)
    ImageButton mMsgBtn;
    @BindView(R.id.txt_title)
    TextView mShopCarTitlt_tv;
    @BindView(R.id.btn_top_edit)
    Button mShopCarEditBtn;
    /**
     * 购物车不为null  有商品的layout
     */
    @BindView(R.id.shopCar__Goods_Show)
    RecyclerView mShopGoodShowView;
    LinearLayoutManager mLinearLayoutManager;
    LinearLayoutManager mLinearLayoutManagerRecommend;
    @BindView(R.id.shopCar_show_layout)
    RelativeLayout mShopCarGoodsShowLayout;
    /**
     * 展示购物车商品时的loading
     */
    @BindView(R.id.lay_loading)
    RelativeLayout mShowGoodsLoadLayout;
    @BindView(R.id.lay_loading_txt)
    TextView mLoadingTxt;

    /**
     * 结算全选 & 删除全选
     */
    @BindView(R.id.shopCar_acctount_allSelect)
    LinearLayout mAllSelect;
    @BindView(R.id.shopCar_delete_AllSelect)
    LinearLayout mAllDelect;

    /**
     * 全选按钮
     */
    @BindView(R.id.shopCar_account_allSelect_icon)
    ImageView mSelectAllAccountIcon;
    @BindView(R.id.shopCar_delete_allSelect_icon)
    ImageView mSelectAllDeleteIcon;
    /**
     * 商品总价
     */
    @BindView(R.id.shopCar_allMoney)
    TextView mAllMoeny;
    /**
     * 商品结算（下订单）  &  商品删除
     */
    @BindView(R.id.shopCar_goToAccount)
    LinearLayout mGoToAccount;
    @BindView(R.id.shopCar_delteGoodsBtn)
    TextView mDelectGoods;

    /**
     * 购物车底部编辑layout
     */
    @BindView(R.id.shopCar_EditLayout)
    RelativeLayout mShopEditLayout;
    @BindView(R.id.shopCar_deleteLayout)
    RelativeLayout mDeleteLayout;
    @BindView(R.id.shopCar_AccountsLayout)
    RelativeLayout mAccountLayout;
    /**
     * "结算" 全选状态  &  "删除" 全选状态
     */
    private boolean mAllAccountStatus, mAllDeleteStatus;
    /**
     * 选中的商品数量
     */
    @BindView(R.id.shopCar_Account_goods_count)
    TextView mCheckGoodsCount;
    @BindView(R.id.edit_layout_divider)
    RelativeLayout mEditLayoutDivider;
    /**
     * 空购物车
     */
    @BindView(R.id.shopcar_null_layout)
    RelativeLayout mShopCarNullLayout;
    @BindView(R.id.shopCar_null_layout_refresh)
    SwipeRefreshLayout mShopCarNullDataLayoutRefresh;
    /**
     * 推荐商品列表
     */
    @BindView(R.id.shopCar_recommend_goods)
    RecyclerView mRecommendGoodsRecyclerView;
    /**
     * 连接服务器失败
     */
    @BindView(R.id.connect_net_error_layout)
    LinearLayout mConnectErrorLayout;
    @BindView(R.id.re_query_data_layout)
    LinearLayout mReQueryDataLL;

    @BindView(R.id.refreshShopCarLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;

    /**
     * 商品选中状态drawable
     */
    private Drawable left;
    private Drawable right;

    /**
     * 当前的状态为  "结算" or "编辑删除"
     */
    private boolean isAccount = true;
    /**
     * 购物车适配器
     */
    private ShopCarAdapter mShopCarAdapter;

    /**
     * 选中的item数量
     */
    private int checkGoodsCount = 0;

    /**
     * 推荐商品adapter
     */
    private ShopCarRecommendAdapter mShopCarRecommendAdapter;
    private List<TerminalEntiyt> mRecommendGoods;
    /**
     * 购物车数据代理集合
     */
    private List<ShopCarGoodsModel> mGoods;
    /**
     * 失效的商品集
     */
    private List<ShopCarGoodsModel> mFailureGoods;
    /**
     * 选中商品集
     */
    private Map<Integer, Boolean> mCheckMap;
    /**
     * 未失效商品集合
     */
    private Map mNormalGoods;

    /**
     * 当前刷新动画是否显示  如果显示则不加载动画
     * 如果没有显示 则显示加载动画
     */
    private boolean isRefresh = false;
    private boolean isRecommendRefresh = false;

    /**
     * 去提交订单时 携带的初订单信息key值
     */
    private static final String SHOPCAR_ORDER_INFO_KEY = "orderInfo";

    private static final int SHOPCAR_RESULT_OK_CODE = 10;
    /**
     * 跳转到生成订单页的request值
     */
    private static final int SHOPCAR_ORDER_REQUEST_CODE = 1;

    public static ShopCarFragment newInstance(String tabName) {
        ShopCarFragment shopCarFragment = new ShopCarFragment();
        shopCarFragment.tag = tabName;
        return shopCarFragment;
    }

    @Override
    public void setTheme() {
        ScreenUtil.setStatusBarDarkFont(_mActivity,true);
    }

    @Override
    public int setLayoutID() {
        return R.layout.fragment_shoppingcart;
    }
    @Override
    public void onSupportVisible() {
//        setSpecificTitleLayout(mStatusView);
        super.onSupportVisible();
//        mImmersionBar.statusBarDarkFont(true).statusBarColor(R.color.white).init();
    }
    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        EventBus.getDefault().register(this);
        left = getResources().getDrawable(R.mipmap.shopcar_goods_uncheckselected);
        right = getResources().getDrawable(R.mipmap.shopcar_goods_checkselected);
        initView();
        bindData();
    }


    @Override
    public void initView() {
        super.initView();
        mShopCarTitlt_tv.setText("购物车");
        mLinearLayoutManager = new LinearLayoutManager(mFragmentContext);
        mLinearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mLinearLayoutManagerRecommend = new LinearLayoutManager(mFragmentContext);
        mLinearLayoutManagerRecommend.setOrientation(LinearLayoutManager.VERTICAL);

        mSwipeRefreshLayout.setColorSchemeColors(Color.rgb(223, 47, 47));
        mShopCarNullDataLayoutRefresh.setColorSchemeColors(Color.rgb(223, 47, 47));
        // 购物车不为空状态下的adapter
        mShopCarAdapter = new ShopCarAdapter(mFragmentContext);
        mGoods = new ArrayList<>();
        mShopCarAdapter.setGoodsList(mGoods);
        mShopGoodShowView.setLayoutManager(mLinearLayoutManager);
        mShopGoodShowView.setAdapter(mShopCarAdapter);

        // 购物车为空状态的推荐商品的adapter
        mShopCarRecommendAdapter = new ShopCarRecommendAdapter(mFragmentContext);
        mRecommendGoodsRecyclerView.setLayoutManager(mLinearLayoutManagerRecommend);
        mRecommendGoodsRecyclerView.setLayoutManager(mLinearLayoutManagerRecommend);
        mRecommendGoodsRecyclerView.setNestedScrollingEnabled(false);
        mRecommendGoodsRecyclerView.getLayoutParams().height = CommonUtils.getScreenHeight(mFragmentContext) - CommonUtils.dp2px(mFragmentContext, 100);
        mRecommendGoodsRecyclerView.setAdapter(mShopCarRecommendAdapter);

        mConnectErrorLayout.setVisibility(View.GONE);
        mShopCarGoodsShowLayout.setVisibility(View.GONE);
    }

    @Override
    public void bindData() {
        super.bindData();

        getShopCarGoodsFromDS(null, null, null);
        mReQueryDataLL.setOnClickListener(this);
        /**
         * 编辑按钮
         */
        mShopCarEditBtn.setOnClickListener(this);

        mAllSelect.setOnClickListener(this);

        mAllDelect.setOnClickListener(this);

        mGoToAccount.setOnClickListener(this);

        mDelectGoods.setOnClickListener(this);

        /**
         * 购物车为空状态下的加载更多
         */
        mShopCarNullDataLayoutRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                isRefresh = true;
                isRecommendRefresh = true;
                getShopCarGoodsFromDS(NORMAL, null, null);
            }
        });

        /**
         * 刷新购物车数据
         */
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                isRefresh = true;
                isRecommendRefresh = true;
                getShopCarGoodsFromDS(null, null, null);
            }
        });

        /**
         * 商品单选
         */
        mShopCarAdapter.setGoodsSelectListener(new GoodsSelectStatusListener() {
            @Override
            public void setGoodsSelectStatusResult(View itemView, int position, boolean isCheck) {
                if (!isCheck) {
                    mAllAccountStatus = false;
                    mAllDeleteStatus = false;
                    mSelectAllAccountIcon.setImageDrawable(left);
                    mSelectAllDeleteIcon.setImageDrawable(left);
                }
                //选中的商品的数量
                int i = 0;
                //失效的商品的数量
                int j = 0;
                mGoods.get(position).setIsCheck(isCheck);
                for (ShopCarGoodsModel dbGoodsCartModel : mGoods) {
                    if (dbGoodsCartModel.getIsCheck()) {
                        i++;
                    }
                    if (dbGoodsCartModel.getGoodsStatus() != 1) {
                        j++;
                    }
                }
                if (i + j == mGoods.size() && mGoods.size() != 0) {
                    mAllAccountStatus = true;
                    mAllDeleteStatus = true;
                    mSelectAllAccountIcon.setImageDrawable(right);
                    mSelectAllDeleteIcon.setImageDrawable(right);
                }
                GreenDaoOperateHelper.updateGoods(mGoods.get(position));
                AccountPrice();
            }
        });

        mShopCarAdapter.setDelFailureGoodsListener(new ShopCarDelFailureGoodsListener() {
            @Override
            public void setOnDelFailureGoodsListener() {
                mFailureGoods = new ArrayList<ShopCarGoodsModel>();
                for (ShopCarGoodsModel dbGoodsCartModel : mGoods) {
                    if (dbGoodsCartModel.getGoodsStatus() == 0) {
                        dbGoodsCartModel.setAction("del");
                        mFailureGoods.add(dbGoodsCartModel);
                    }
                }
                getShopCarGoodsFromDS(DEL, mFailureGoods, mFailureGoods);
            }
        });
        /**
         * 商品数量增减
         */
        mShopCarAdapter.setGoodsCountChangeListener(new GoodsCountChangeListener() {
            @Override
            public void setCountChange(int position, String count, boolean isAdd) {
                /**
                 * 如果商品数量小于1  直接退出本次处理
                 */
                if (Integer.valueOf(count) < 1) {
                    if (Integer.valueOf(count) < 0) {
                        return;
                    }
                }
                int resultNum = Integer.valueOf(count);
                List<ShopCarGoodsModel> mEditGoodsList = new ArrayList<ShopCarGoodsModel>();
                ShopCarGoodsModel dbGoodsCartModel = mGoods.get(position);
                if (resultNum - 1 > dbGoodsCartModel.getGoodsAllNum()) {
                    dbGoodsCartModel.setIsCheck(false);
                } else {
                    dbGoodsCartModel.setIsCheck(true);
                }
                dbGoodsCartModel.setGoodsNum(resultNum);
                dbGoodsCartModel.setAction("update");
                mEditGoodsList.add(dbGoodsCartModel);
                getShopCarGoodsFromDS(UPDATE, mEditGoodsList, mEditGoodsList);
            }
        });
    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {
        getShopCarGoodsFromDS(NORMAL, new ArrayList<ShopCarGoodsModel>(), null);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.re_query_data_layout:
                mConnectErrorLayout.setVisibility(View.GONE);
                getShopCarGoodsFromDS(NORMAL, null, null);
                break;
            case R.id.btn_top_edit:
                /**
                 * 右上角编辑
                 */
                mCheckGoodsCount.setText("(0)");
                mSelectAllAccountIcon.setImageDrawable(left);
                mSelectAllDeleteIcon.setImageDrawable(left);
                ShopCarGoodsModel dbGoodsCartModel;
                for (int i = 0; i < mGoods.size(); i++) {
                    dbGoodsCartModel = mGoods.get(i);
                    dbGoodsCartModel.setIsCheck(false);
                    GreenDaoOperateHelper.updateGoods(dbGoodsCartModel);
                }
                mAllDeleteStatus = false;
                mAllAccountStatus = false;
                mAllMoeny.setText("  0");
                mShopCarAdapter.setGoodsList(mGoods);
                if (isAccount) {
                    isAccount = !isAccount;
                    mAccountLayout.setVisibility(View.GONE);
                    mDeleteLayout.setVisibility(View.VISIBLE);
                    mShopCarEditBtn.setText("完成");
                } else {
                    isAccount = !isAccount;
                    mDeleteLayout.setVisibility(View.GONE);
                    mAccountLayout.setVisibility(View.VISIBLE);
                    mShopCarEditBtn.setText("编辑");
                }
                mShopCarAdapter.setSelectType(isAccount);
                break;
            case R.id.shopCar_acctount_allSelect:
                /**
                 * 点击全选
                 * 计算总价
                 *      改变状态
                 *      遍历集合
                 *      并将集合中所有的item的状态值进行改变
                 *      刷新适配器
                 */
                if (mNormalGoods.size() == 0) {
                    showSystemToast("请先选择商品");
                    break;
                }
                mAllAccountStatus = !mAllAccountStatus;
                int clickNum = 0;
                if (mAllAccountStatus) {
                    for (int i = 0; i < mGoods.size(); i++) {
                        /**
                         * 全选状态
                         *          如果商品数量小于1 则设为不选中状态
                         */
                        if (mGoods.get(i).getGoodsNum() < 1 || mGoods.get(i).getGoodsNum() < 1 || mGoods.get(i).getGoodsAllNum() < mGoods.get(i).getGoodsNum() || mGoods.get(i).getGoodsStatus() != 1) {
                            mGoods.get(i).setIsCheck(false);
                        } else {
                            mGoods.get(i).setIsCheck(true);
                            clickNum++;
                        }
                        GreenDaoOperateHelper.updateGoods(mGoods.get(i));
                        if (clickNum > 0) {
                            mSelectAllAccountIcon.setImageDrawable(right);
                        } else {
                            showDialog(null, "您购物车的商品库存不足，请去添加新商品");
                        }
                    }
                } else {
                    mSelectAllAccountIcon.setImageDrawable(left);
                    for (int i = 0; i < mGoods.size(); i++) {
                        mGoods.get(i).setIsCheck(false);
                        GreenDaoOperateHelper.updateGoods(mGoods.get(i));
                    }
                }
                AccountPrice();
//                mShopCarAdapter.setClearData();
                mShopCarAdapter.setGoodsList(mGoods);
                break;
            case R.id.shopCar_delete_AllSelect:
                /**
                 * 点击全选
                 * 删除商品
                 *      改变状态
                 *      遍历集合
                 *      并将集合中所有的item的状态值进行改变
                 *      刷新适配器
                 *
                 */
                if (mNormalGoods.size() == 0) {
                    showSystemToast("请先选择商品");
                    return;
                }
                mAllDeleteStatus = !mAllDeleteStatus;
                if (mAllDeleteStatus) {
                    mSelectAllDeleteIcon.setImageDrawable(right);
                    for (int i = 0; i < mGoods.size(); i++) {
                        mGoods.get(i).setIsCheck(true);
                        GreenDaoOperateHelper.updateGoods(mGoods.get(i));
                    }
                } else {
                    mSelectAllDeleteIcon.setImageDrawable(left);
                    for (int i = 0; i < mGoods.size(); i++) {
                        mGoods.get(i).setIsCheck(false);
                        GreenDaoOperateHelper.updateGoods((mGoods.get(i)));
                    }
                }
                mShopCarAdapter.setGoodsList(mGoods);
                // 改变选中的状态
                break;
            case R.id.shopCar_goToAccount:
                /**
                 * 去结算
                 */
                if (mNormalGoods.size() == 0) {
                    showSystemToast("请先选择商品");
                    return;
                }
                if (!isUserLogin()) {
                    showLoginDialog();
                    return;
                }
                ArrayList<ShopCarGoodsModel> mOrderInfo = new ArrayList<>();
                for (ShopCarGoodsModel goodsEntity : mGoods) {
                    if (goodsEntity.getIsCheck()) {
                        mOrderInfo.add(goodsEntity);
                    }
                }
                if (mOrderInfo.size() == 0) {
                    showDialog(null, "请先选择要购买的商品");
                    return;
                }
                Intent intent = new Intent(getContext(), ToCreateOrderActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString(SHOPCAR_ORDER_INFO_KEY, JSON.toJSONString(mOrderInfo));
                intent.putExtras(bundle);
                startActivityForResult(intent, SHOPCAR_ORDER_REQUEST_CODE);
                getActivity().overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
                break;
            case R.id.shopCar_delteGoodsBtn:
                /**
                 * 删除商品
                 */
                if (mNormalGoods.size() == 0) {
                    showSystemToast("请先选择商品");
                    return;
                }
                /**
                 * 全选状态改变
                 */
                mSelectAllDeleteIcon.setImageDrawable(left);
                mAllDeleteStatus = false;

                ArrayList<ShopCarGoodsModel> mDelGoodsList = new ArrayList<>();
                Iterator iterator = mGoods.iterator();
                while (iterator.hasNext()) {
                    ShopCarGoodsModel goodEntity = (ShopCarGoodsModel) iterator.next();
                    if (goodEntity.getIsCheck() && goodEntity.getGoodsStatus() == 1) {
                        goodEntity.setAction("del");
                        mDelGoodsList.add(goodEntity);
                    }
                }
                getShopCarGoodsFromDS(DEL, mDelGoodsList, mDelGoodsList);
                break;
            default:
                break;
        }
    }

    @Override
    public void showLoading() {
        if (mShowGoodsLoadLayout != null) {
            mShowGoodsLoadLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void hideLoading() {
        if (mShowGoodsLoadLayout != null && mShopCarNullDataLayoutRefresh != null && mSwipeRefreshLayout != null) {
            mShowGoodsLoadLayout.setVisibility(View.GONE);
            mShopCarNullDataLayoutRefresh.setRefreshing(false);
            mSwipeRefreshLayout.setRefreshing(false);
        }
    }

    @Override
    public void notifyAdapter(List<ShopCarGoodsModel> goodsEntities) {
        int selectNum = 0;
        if (!UserLoginInfo.isUserLogin() && goodsEntities != null) {
            Collections.reverse(goodsEntities);
        }
        if (mRecommendGoodsRecyclerView == null) {
            return;
        }
        mNormalGoods = new HashMap();
        mGoods = goodsEntities;
        // 获取未失效商品集
        if (mGoods != null) {
            for (ShopCarGoodsModel dbGoodsCartModel : mGoods) {
                if (dbGoodsCartModel.getGoodsStatus() == 1) {
                    mNormalGoods.put(dbGoodsCartModel.getGoodsID(), true);
                    if (dbGoodsCartModel.getIsCheck()) {
                        selectNum++;
                    }
                }
            }
        }
        // 清除选中商品集中的无效商品
        if (mCheckMap != null) {
            if (mGoods == null || mGoods.size() == 0) {
                mCheckMap.clear();
            } else {
                ArrayList<Integer> arrayList = new ArrayList<>();
                for (ShopCarGoodsModel checkGoods : mGoods) {
                    arrayList.add(checkGoods.getGoodsID());
                }
                Iterator<Integer> integerIterator = mCheckMap.keySet().iterator();
                while (integerIterator.hasNext()) {
                    Integer goodsID = integerIterator.next();
                    if (!arrayList.contains(goodsID)) {
                        integerIterator.remove();
                        mCheckMap.remove(goodsID);
                    }
                }
            }
        } else {
            mCheckMap = new HashMap<>(16);
        }
        // 根据选中商品集 将新商品集中的商品设置选中状态
        if (mCheckMap != null) {
            for (Integer goodsID : mCheckMap.keySet()) {
                for (ShopCarGoodsModel dbGoodsCartModel : mGoods) {
                    if (dbGoodsCartModel.getGoodsID() == goodsID) {
                        LogUtils.i("测试：" + dbGoodsCartModel.toString());
                        dbGoodsCartModel.setIsCheck(true);
                    }
                }
            }
        }
        /**
         * 首次进入 有效商品集中有选中状态的商品  但是选中商品集的数量为0  需要根据有效商品集中的商品选中状态的数量判断是否将全选改为选中状态
         * 非首次进入
         */
        if (mGoods != null) {
            if (mCheckMap.size() < mNormalGoods.size() && mCheckMap.size() != 0) {
                // 如果选中商品集中的商品数量 < 有效商品集的数量   并且选中商品集的商品数量不为0  则设置全选状态为未选中
                mAllDeleteStatus = false;
                mAllAccountStatus = false;
                mSelectAllAccountIcon.setImageDrawable(left);
                mSelectAllDeleteIcon.setImageDrawable(left);
            } else if ((mCheckMap.size() == mNormalGoods.size() && mCheckMap.size() != 0)) {
                mAllDeleteStatus = true;
                mAllAccountStatus = true;
                mSelectAllAccountIcon.setImageDrawable(right);
                mSelectAllDeleteIcon.setImageDrawable(right);
            } else if (selectNum == mNormalGoods.size() && mNormalGoods.size() != 0) {
                mAllDeleteStatus = true;
                mAllAccountStatus = true;
                mSelectAllAccountIcon.setImageDrawable(right);
                mSelectAllDeleteIcon.setImageDrawable(right);
            } else {
                mAllDeleteStatus = false;
                mAllAccountStatus = false;
                mSelectAllAccountIcon.setImageDrawable(left);
                mSelectAllDeleteIcon.setImageDrawable(left);
            }
        }
        mConnectErrorLayout.setVisibility(View.GONE);

        mShopCarAdapter.setGoodsList(mGoods);

        hideLoading();
        AccountPrice();
        if (mGoods == null || mGoods.size() == 0) {
            /**  如果购物车没有商品  则
             * 编辑状态改变
             */
            isAccount = true;
            mShopCarAdapter.setSelectType(isAccount);
            mDeleteLayout.setVisibility(View.GONE);
            mAccountLayout.setVisibility(View.VISIBLE);
            mShopCarEditBtn.setText("编辑");


            mShopCarNullLayout.setVisibility(View.VISIBLE);

            mShopCarGoodsShowLayout.setVisibility(View.GONE);
            mShopEditLayout.setVisibility(View.GONE);
            mEditLayoutDivider.setVisibility(View.GONE);
            mShopCarEditBtn.setVisibility(View.GONE);
//            mMsgBtn.setVisibility(View.GONE);
            getShopCarRecommendGoods();
        } else {
            mShopCarNullLayout.setVisibility(View.GONE);
            mShopCarGoodsShowLayout.setVisibility(View.VISIBLE);
            mEditLayoutDivider.setVisibility(View.VISIBLE);
            mShopEditLayout.setVisibility(View.VISIBLE);
            mShopCarEditBtn.setVisibility(View.VISIBLE);
//            mMsgBtn.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void AccountPrice() {
        // 商品总价 string
        String strPrice = "0";
        // 商品总价
        double price = 0;
        checkGoodsCount = 0;
        if (mGoods != null) {
            for (ShopCarGoodsModel goodsEntity : mGoods) {
                if (goodsEntity.getIsCheck()) {
                    BigDecimal a1 = new BigDecimal(String.valueOf(goodsEntity.getGoodsPrice()));
                    BigDecimal a2 = new BigDecimal(String.valueOf(goodsEntity.getGoodsNum()));
                    checkGoodsCount += goodsEntity.getGoodsNum();
                    BigDecimal result = a1.multiply(a2);

                    BigDecimal one = new BigDecimal("1");
                    price += result.divide(one, 2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    DecimalFormat df = new DecimalFormat("######0.00");
                    strPrice = df.format(price);
                }
            }
        }
        mCheckGoodsCount.setText("(" + checkGoodsCount + ")");
        mAllMoeny.setText("¥ " + strPrice);
    }

    @Override
    public void getShopCarRecommendGoods() {
        if (!isRecommendRefresh) {
            showLoading();
        }
        isRecommendRefresh = false;
        mPrecenter.loadRecommentGoods();
    }

    @Override
    public void setShopCarRecommendGoods(List<TerminalEntiyt> goodsEntities) {
        mShopCarNullLayout.setVisibility(View.VISIBLE);
        hideLoading();
        mRecommendGoods = goodsEntities;
        if (mRecommendGoods != null) {
            if (mRecommendGoods.size() == 0) {

            } else {
                mShopCarRecommendAdapter.setGoodArray(mRecommendGoods);
            }
        }
    }

    @Override
    public void showErrorDialog(String failReason) {
        showDialog(null, failReason);
    }

    @Override
    public void showNetErrorLayout() {
        if (mShopCarNullDataLayoutRefresh != null && mSwipeRefreshLayout != null && mShopCarEditBtn != null && mShopCarNullLayout != null && mShopCarGoodsShowLayout != null && mConnectErrorLayout != null) {
            mShopCarNullDataLayoutRefresh.setRefreshing(false);
            mSwipeRefreshLayout.setRefreshing(false);
            mShopCarEditBtn.setVisibility(View.GONE);
            mShopCarNullLayout.setVisibility(View.GONE);
            mShopCarGoodsShowLayout.setVisibility(View.GONE);
            mConnectErrorLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void setOrderInfo(String orderInfo) {

    }

    @NonNull
    @Override
    public AbBasePrecenter initPresenter() {
        return ShopCarMainPrecenter.create();
    }


    /**
     * @param editType            操作数据库的类型  NOMAL  || NULL  正常获取服务器数据   UPDATA 修改数据库商品数量   DEL  删除商品
     *                            用来判断 连接服务器异常之后   如果为NOMAL || NULL 则从数据库获取商品  并展示  如果 为UPDATA || DEL 则提示 连接服务器异常
     * @param updateToServiceData 需要同步到服务器的商品集
     * @param updateToLocalData   同步到本地数据库的商品集
     */
    public void getShopCarGoodsFromDS(String editType, List<ShopCarGoodsModel> updateToServiceData, List<ShopCarGoodsModel> updateToLocalData) {
        /**
         *      如果已登录
         *              获取本地数据库数据  (并获取更新标识--已处理) 如果已更新到服务器 则从服务器获取数据  如果未更新 则 更新到服务器
         *      如果未登录 则从本地数据库获取商品
         *
         */
        saveSelectGoodsID(mGoods);

        if (isUserLogin()) {
            if (!isRefresh) {
                showLoading();
            }
            isRefresh = false;
            if (updateToServiceData != null) {
                // 如果需要将本地数据同步到服务器（只适用于购物车的商品数量的变化   以及商品的删除 ）
                List<ShopCarGoodsModel> data = new ArrayList<>();
                data.addAll(updateToServiceData);
                if (mGoods == null) {
                    mGoods = GreenDaoOperateHelper.getAllGoods();
                    if (mGoods == null) {
                        mGoods = new ArrayList<>();
                    }
                }
                for (ShopCarGoodsModel dbGoodsCartModel : mGoods) {
                    if (!data.contains(dbGoodsCartModel)) {
                        data.add(dbGoodsCartModel);
                    }
                }
                Iterator iterator = data.iterator();
                while (iterator.hasNext()) {
                    ShopCarGoodsModel dbGoodsCartModel = (ShopCarGoodsModel) iterator.next();
                    // 筛选掉action为空的数据
                    if (TextUtils.isEmpty(dbGoodsCartModel.getAction())) {
                        iterator.remove();
                    }
                }
                mPrecenter.editShopCarGoodsToService(data);
            } else {
                // 如果不需要 则直接获取服务端数据
                mPrecenter.editShopCarGoodsToService(null);
            }
        } else { // 如果没有登陆
            if (updateToLocalData != null) {
                // 修改购物车数据  则
                mPrecenter.editShopCarGoodsToLocal(editType, updateToLocalData);
            } else {
                // 只适用于单纯获取本地购物数据 并展示
                mPrecenter.getShopCarGoodsFromLocal();
            }
        }
    }

    /**
     * 同步服务器前的数据   如果有选中的则将选中的商品id保存下来
     */
    private void saveSelectGoodsID(List<ShopCarGoodsModel> mSelectGoods) {
        if (mSelectGoods != null) {
            if (mCheckMap == null) {
                mCheckMap = new HashMap<>();
            }
            mCheckMap.clear();
            for (ShopCarGoodsModel dbGoodsCartModel : mSelectGoods) {
                if (dbGoodsCartModel.getIsCheck()) {
                    mCheckMap.put(dbGoodsCartModel.getGoodsID(), true);
                }
            }
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        // 暂无调用
        if (resultCode == SHOPCAR_RESULT_OK_CODE) {
            if (requestCode == SHOPCAR_ORDER_REQUEST_CODE) {
                mPrecenter.editShopCarGoodsToService(null);
                getShopCarGoodsFromDS(NORMAL, null, null);
            }
        }
    }


    @Override
    public boolean onBackPressedSupport() {
        if (getActivity() instanceof MyShopCartActivity) {
            return super.onBackPressedSupport();
        }
        if (mShowGoodsLoadLayout != null && mShowGoodsLoadLayout.getVisibility() == View.VISIBLE) {
            return false;
        }
        return true;
    }

    /**
     * 本地数据库购物车商品集
     */
    @Override
    public void onResume() {
        super.onResume();
        if (mAllSelect != null && mAllDelect != null) {
        }
        // 如果是从生产订单成功界面返回  并且已经生产订单成功 则需要刷新获取购物车数据
        if (PreferenceTools.getBoolean("orderIsSuccess", false)) {
            PreferenceTools.putBoolean("orderIsSuccess", false);
            if (mPrecenter != null) {
                getShopCarGoodsFromDS(NORMAL, null, null);
            }

        }
    }

    /**
     * 终端列表页添加购物车成功之后   获取本地数据集  刷新界面
     *
     * @param updateCartMessage
     */
    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onEditAdr(UpdateCartMessage updateCartMessage) {
        // 同步服务器前的数据   如果有选中的则 将选中的商品id保存下来
        if(updateCartMessage.getAction().equals(UpdateCartMessage.GOTO_SERVICE_GET_DATA)){
            getShopCarGoodsFromDS(null,null,null);
        }else {
            saveSelectGoodsID(mGoods);
            mPrecenter.getShopCarGoodsFromLocal();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden){
            if(!(_mActivity instanceof HomeActivity)){
                return;
            }
            if (((HomeActivity) _mActivity).isHaveNewMsg) {
                mMsgBtn.setImageResource(R.mipmap.unread_msg);
            } else {
                mMsgBtn.setImageResource(R.mipmap.message_normal_icon);
            }
        }
    }

    @Override
    public void loadDataComplated() {

    }

    @Override
    public void loadDataError() {

    }
}
